package edu.nf.relaxenjoy.web.interceptor;

import com.alibaba.fastjson.JSON;
import edu.nf.relaxenjoy.common.constant.Constant;
import edu.nf.relaxenjoy.common.constant.auth.AuthConstant;
import edu.nf.relaxenjoy.common.constant.auth.AuthContextHolder;
import edu.nf.relaxenjoy.common.exception.ErrorsEnum;
import edu.nf.relaxenjoy.common.exception.TokenException;
import edu.nf.relaxenjoy.common.util.JwtUtils;
import edu.nf.relaxenjoy.common.util.RedisUtils;
import edu.nf.relaxenjoy.domain.vo.UserLogin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author zhu
 * @date 2024-12-11
 */
@RequiredArgsConstructor
public class UserLoginInterceptor implements HandlerInterceptor {
    private static final long TIME = 60 * 60 * 24;
    private final RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler){
        //放行OPTIONS请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }

        String token = request.getHeader(Constant.FRONT_TOKEN_HEADER);

        //判断token不为空
        if(!StringUtils.isEmpty(token)) {
            //从token获取userId
            String userId = JwtUtils.getUserId(token);
            Long expire = redisUtils.getExpire(Constant.FRONT_TOKEN_HEADER + userId);
            UserLogin userLogin = JSON.parseObject(redisUtils.get(AuthConstant.USER_KEY + userId), UserLogin.class);
            if(expire<=0){
                throw new TokenException(ErrorsEnum.TOKEN_FAIL);
            } else if(expire<TIME){
                String newToken = JwtUtils.getJwtToken(String.valueOf(userLogin.getId()), userLogin.getPassword());
                redisUtils.setEx(Constant.FRONT_TOKEN_HEADER+userLogin.getId(),newToken,2, TimeUnit.DAYS);
            }

            if(userLogin!=null){
                AuthContextHolder.setUserId(userLogin.getId());
                return true;
            }

        }
        throw new TokenException(ErrorsEnum.TOKEN_FAIL);
    }
}
